﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace PubSub.S3.Common
{
    public class FuncTypeFactory
    {
        private static List<EnumEntity> s_channelCache = null;
        private static object s_locker = new object();

        public static List<EnumEntity> ChannelCache
        {
            get
            {
                if (s_channelCache == null)
                {
                    lock (s_locker)
                    {
                        var cache = EnumHelper.EnumToList<FuncTypeEnum>();

                        //检查是否有重复的通道名称乐
                        var groups = cache.GroupBy(e => e.Name);
                        if (groups.Any(gp => gp.Count() > 1))
                        {
                            throw new SystemException($"{nameof(FuncTypeEnum)}中存在重复的通道名称");
                        }

                        s_channelCache = cache;
                    }
                }

                return s_channelCache;
            }
        }

        public static string GetChannelString(FuncTypeEnum type)
        {
            if (ChannelCache != null)
            {
                return ChannelCache.FirstOrDefault(e => e.Value == (int) type)?.Name;
            }

            return null;
        }

        /// <summary>
        /// 是否有效枚举值类型
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static bool IsValidType(int type)
        {
            if (ChannelCache != null)
            {
                var match = ChannelCache.FirstOrDefault(e => e.Value == (int) type);
                return match != null;
            }

            return false;
        }

        /// <summary>
        /// 是否有效通道名称
        /// </summary>
        /// <param name="channel"></param>
        /// <returns></returns>
        public static bool IsValidChannelName(string channel)
        {
            if (ChannelCache != null)
            {
                var match = ChannelCache.FirstOrDefault(e =>
                    string.Equals(e.Name, channel, StringComparison.OrdinalIgnoreCase)); //大小写不敏感
                return match != null;
            }

            return false;
        }
    }
}